//
//  ProjectBidsViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ProjectBidsViewController.h"
#import "ProjectBidsTableViewCell.h"
#import "ProjectTypeTableViewCell.h"
#import "ProjectBidsDetailViewController.h"
static NSString * cellIndentifier = @"ProjectBidsTableViewCell";
static NSString * CellIndentifier = @"ProjectTypeTableViewCell";

@interface ProjectBidsViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *neButton;
@property (weak, nonatomic) IBOutlet UIButton *bodyButton;
@property (weak, nonatomic) IBOutlet UITableView *typeTableView;
@property (weak, nonatomic) IBOutlet UIButton *maskButton;
@property(nonatomic,strong)NSMutableArray * bidsArray;
@property(nonatomic,strong)NSIndexPath * selctedPath;
@end

@implementation ProjectBidsViewController
- (void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _bidsArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.buttonView];

    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    
    [_typeTableView registerNib:[UINib nibWithNibName:CellIndentifier bundle:nil] forCellReuseIdentifier:CellIndentifier];
    _typeTableView.dataSource = self;
    _typeTableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark === 最新发布点击
- (IBAction)newPost:(UIButton *)sender {
    sender.selected = YES;
    _bodyButton.selected = NO;
    _maskButton.hidden = YES;
    _typeTableView.frame = flexibleFrame(CGRectMake(0, 112, 320, 0), NO);
    _selctedPath = nil;
    [_tableView.header beginRefreshing];
}
#pragma mark === 招标主体点击
- (IBAction)bodyHandel:(UIButton *)sender {
    sender.selected = !sender.selected;
    _neButton.selected = NO;
    if (sender.selected) {
        _typeTableView.frame = flexibleFrame(CGRectMake(0, 112, 320, 80), NO);
        _maskButton.hidden = NO;

    }else{
      _typeTableView.frame = flexibleFrame(CGRectMake(0, 112, 320, 0), NO);
        _maskButton.hidden = YES;
    }
}


- (IBAction)maskButtonHandel:(id)sender {
    _typeTableView.frame = flexibleFrame(CGRectMake(0, 112, 320, 0), NO);
    _maskButton.hidden = YES;
    _bodyButton.selected = NO;
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getBidsList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.bidsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getBidsList];
        });
    }
    
}

#pragma mark === 获取招标列表
- (void)getBidsList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    if (_selctedPath) {
        if (_selctedPath.row == 0) {
            [dic setObject:@"4" forKey:@"museType"];
        }else{
            [dic setObject:@"2" forKey:@"museType"];
        }
    }
    self.shareApi.delegate=self;
    
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMallMarketDemandList withHttpType:@"POST" withTag:GS_GS_queryMallMarketDemandList];
    
    
}




#pragma mark  ==== tableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return _bidsArray.count;
    }else{
        return 2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        return 147*VerticalRatio();
    }else{
        return 40*VerticalRatio();
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (tableView == _tableView) {
        ProjectBidsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[ProjectBidsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        
        NSDictionary * dic = _bidsArray[indexPath.row];
        
        cell.bidName.text = [NSString stringWithFormat:@"%@",dic[@"mmdeName"]];
        cell.address.text = [NSString stringWithFormat:@"%@%@",dic[@"citySysArea"][@"AName"],dic[@"proSysArea"][@"AName"]];
        cell.time.text = [NSString stringWithFormat:@"%@",dic[@"mmdeCreateTime"]];
        cell.request.text = [NSString stringWithFormat:@"%@",dic[@"mmdeContent"]];
        cell.personName.text = [NSString stringWithFormat:@"%@",dic[@"mstoMemberName"]];
        cell.companyName.text = [NSString stringWithFormat:@"%@",dic[@"mstoName"]];
        cell.scanNum.text = [NSString stringWithFormat:@"%@浏览",dic[@"mmdeReadTimes"]];
        
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mstoImage"]];
        [cell.companyIMage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        
        return cell;
        

    }else{
        ProjectTypeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (cell == nil) {
            cell = [[ProjectTypeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
        }
        NSArray * array = @[@"工程公司",@"石材商"];
        cell.typeName.text = array[indexPath.row];
        cell.typeName.textColor = [UIColor colorWithWhite:0.325 alpha:1.000];
        if (indexPath.row == _selctedPath.row) {
            cell.typeName.textColor = [UIColor colorWithRed:0.000 green:0.584 blue:0.867 alpha:1.000];
        }
        
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView == _typeTableView) {
        _bodyButton.selected = NO;
        _typeTableView.frame = flexibleFrame(CGRectMake(0, 112, 320, 0), NO);
        _maskButton.hidden = YES;
        _bodyButton.selected = NO;

        _selctedPath = indexPath;
        NSArray * array = @[@"工程公司",@"石材商"];
        [_bodyButton setTitle:array[indexPath.row] forState:UIControlStateNormal];
        [_typeTableView reloadData];
        [_tableView.header beginRefreshing];

    }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            ProjectBidsDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"ProjectBidsDetail"];
            page.bidId = _bidsArray[indexPath.row][@"mmdeId"];
            [[Common getNavigation]pushViewController:page];
    }
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==GS_GS_queryMallMarketDemandList ) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.bidsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.bidsArray addObject:entity];
                }
                
                [_tableView reloadData];
                
            });
            
        }
        
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
